<?php
namespace Cadss\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Cadss\TestBundle\Entity\Document;
use Cadss\TestBundle\Entity\Keyword;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Finder;

class DefaultController extends Controller
{
  	public function indexAction(Request $request, $id)
    {
    	
	        $data = array();
	        $form = $this->CreateFormBuilder($data)
	            /*->setAction($this->generateUrl('cadss_test_search'))*/
	            ->setMethod('GET')
	            ->add('searchterm', 'search', array(
	                'label' => 'Keyword',
					'required' => false))
	            ->add('search', 'submit')
	            ->getForm();
	        
	        $form->handleRequest($request);
			

	        if($form->isValid()){
	            $data = $form["searchterm"]->getData();

	            $repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');     
	            $files = $repositoryDocument->findAll();
	            $finder = new Finder();
	            $finder->files()->in(__DIR__.'/../../../../web/uploads');

				$files_match = array();
				foreach($files as $file){				
					if(strpos($file->getDTitel(),$data)!==false)
					{					
						array_push($files_match, $file);
						continue;
					}			
					if(strpos($file->getDDatum()->format('d-m-Y'),$data)!==false)
					{					
						array_push($files_match, $file);
						continue;
					}
					if(strpos($file->getUser()->getUsername(),$data)!==false)
					{					
						array_push($files_match, $file);
						continue;
					}
					if(strpos($file->getDOmschrijving(),$data)!==false)
					{					
						array_push($files_match, $file);
						continue;
					}
					foreach($file->getKeywords() as $keyword)
					{
						if(strpos($keyword->getKeyword(), $data)!==false)
						{					
							array_push($files_match, $file);
							break;
						}
					}
				}
				foreach($finder as $file){
					if(strpos($file->getContents(), $data) !== false){
						$repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');     
	            		print $file->getFileName()."\n";
	            		$file_path = $file->getFileName();
	            		//print $file_name;
	            		$file1 = $repositoryDocument->findOneBypath($file_path);
	            		//print $file1."\n";
						array_push($files_match, $file1);
					}
				}
				if(empty($files_match))
				{
					$files_match = $files;
					if(!empty($data))
					{
						$message = 'No files find for "'.$data.'"';
						$this->get('session')->getFlashBag()->add('message', $message);
					}
				}			

	            return $this->render('CadssTestBundle:Default:index.html.twig', array(
	                    'files' => $files_match, 'keywords' => $keywords, 'form' => $form->createView(),
	                ));
	        }
		if($id==0){
			$repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');
			$files = $repositoryDocument->findAll();

			$repositoryKeyword = $this->getDoctrine()->getRepository('CadssTestBundle:Keyword');          
			$keywords = $repositoryKeyword->findAll();

	        return $this->render('CadssTestBundle:Default:index.html.twig', array('files' => $files, 'keywords' => $keywords, 'form' => $form->createView(),));
	    }else{
	    	$repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');          
       		$files = $repositoryDocument->findAll();
        	$repositoryKeyword = $this->getDoctrine()->getRepository('CadssTestBundle:Keyword');          
        	$keyword = $repositoryKeyword->findOneById($id);
   			return $this->render('CadssTestBundle:Default:index.html.twig', array('files_with_keyword' => $files, 'keyword' => $keyword, 'form' => $form->createView(),));
	    }
    } 	
	
	public function keywordsAction(Request $request)
    {
        $repositoryKeyword = $this->getDoctrine()->getRepository('CadssTestBundle:Keyword');          
        $keywords = $repositoryKeyword->findAll();
		
		$data = array();
        $form = $this->CreateFormBuilder($data)
            /*->setAction($this->generateUrl('cadss_test_search'))*/
            ->setMethod('GET')
            ->add('searchterm', 'search', array(
                'label' => 'Keyword',
				'required' => false))
            ->add('search', 'submit')
            ->getForm();
        
        $form->handleRequest($request);
		

        if($form->isValid()){
            $data = $form["searchterm"]->getData();            
           
			$keywords_match = array();
			foreach($keywords as $keyword){				
				if(strpos($keyword->getKeyword(), $data)!==false)
				{					
					array_push($keywords_match, $keyword);
					continue;
				}
			}		
			if(empty($keywords_match))
			{
				$keywords_match = $keywords;
				if(!empty($data))
				{
					$message = 'No keywords find for "'.$data.'"';
					$this->get('session')->getFlashBag()->add('message', $message);
				}
			}
				
			return $this->render('CadssTestBundle:Default:keywords.html.twig', array('keywords' => $keywords_match, 'form' => $form->createView(), ));
		}

        return $this->render('CadssTestBundle:Default:keywords.html.twig', array('keywords' => $keywords, 'form' => $form->createView(), ));
    }
   	public function keywordsinfoAction($id){
   		$repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');          
        $files = $repositoryDocument->findAll();
        $repositoryKeyword = $this->getDoctrine()->getRepository('CadssTestBundle:Keyword');          
        $keyword = $repositoryKeyword->findOneById($id);
   		return $this->render('CadssTestBundle:Default:keywords_info.html.twig', array('keyword' => $keyword, 'files' => $files));
   	}

    public function addkeywordAction(Request $request){
    	$keyword = new Keyword();
    	$form = $this->CreateFormBuilder($keyword)
    		->add('keyword', 'text', array(
    			'label' => 'Keyword'))
    		->add('Add', 'submit')
    		->getForm();

    	$form->handleRequest($request);

    	if ($form->isValid()) {
	        $em = $this->getDoctrine()->getManager();
			
			$em->persist($keyword);	
	        $em->flush();

	       return $this->container->get('templating')->renderResponse('CadssTestBundle:Default:close.html.twig');
	    }

    	return $this->render('CadssTestBundle:Default:add_keyword.html.twig', array('form' => $form->createView()));
    }
    public function editkeywordAction($id, Request $request){
    	$repositoryKeyword = $this->getDoctrine()->getRepository('CadssTestBundle:Keyword');          
    	$keyword = $repositoryKeyword->findOneById($id);

	   	$form = $this->CreateFormBuilder($keyword)
    		->add('keyword', 'text', array(
    			'label' => 'Keyword'))
    		->add('Edit', 'submit')
    		->getForm();

        $form->handleRequest($request);

    	if ($form->isValid()) {
	        $em = $this->getDoctrine()->getManager();
			
			//$em->persist($file);
			$keyword->setKeyword($form->get('keyword')->getData());
	        $em->flush();

	        return $this->container->get('templating')->renderResponse('CadssTestBundle:Default:close.html.twig');
	    }

    	return $this->render('CadssTestBundle:Default:edit_keyword.html.twig', array('keyword' => $keyword, 'form' => $form->createView()));
    }
    public function deletekeywordAction($id){
        $repositoryKeyword = $this->getDoctrine()->getRepository('CadssTestBundle:Keyword');
        $keyword = $repositoryKeyword->findOneById($id);
        $message = "An error has occurred and the keyword couldn't be deleted";   
		if(isset($keyword))  
			//if($keyword->getDUid() == $this->getUser()->getId() && $id!=0){
				$em = $this->getDoctrine()->getManager();
				$em->remove($keyword);
				$em->flush();
				$message = "Keyword successfully deleted";             
			//}  		
		$this->get('session')->getFlashBag()->add('message', $message);
		return $this->redirect($this->generateUrl('cadss_test_keywords'));  
    }

	public function uploadAction(Request $request){
    	$document = new Document($this->getUser());    	
	    $form = $this->createFormBuilder($document)
			->add('dTitel', 'text', array(
	        	'label'	=>	'Title'))
			->add('dOmschrijving', 'textarea', array(
	        	'label'	=>	'Description'))	        
	        ->add('file', 'file', array('required'    => true))
	        ->add('keywords', 'entity', array(
	        	'class' => 'CadssTestBundle:Keyword',
	        	'property' => 'keyword',
	        	'multiple' => true,
	        	'expanded' => true)) 
			->add('Upload', 'submit')
	        ->getForm();
			
	    $form->handleRequest($request);
		

	    if ($form->isValid()) {
	        $em = $this->getDoctrine()->getManager();
			
			$em->persist($document);
	        $em->flush();
			
	        return $this->container->get('templating')->renderResponse('CadssTestBundle:Default:close.html.twig');
	    }
		
		//$response = array("code" => 100, "form" => $form);
		//return new Response(json_encode($response));
		
		return $this->container->get('templating')->renderResponse('CadssTestBundle:Default:upload.html.twig', array(
            'form' => $form->createView(),
        ));
	}
	public function editdocumentAction($id, Request $request){
		$repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');          
        $document = $repositoryDocument->findOneById($id);

	    $form = $this->createFormBuilder($document)
			->add('dTitel', 'text', array(
	        	'label'	=>	'Title'))
			->add('dOmschrijving', 'textarea', array(
	        	'label'	=>	'Description'))
	        ->add('keywords', 'entity', array(
	        	'class' => 'CadssTestBundle:Keyword',
	        	'property' => 'keyword',
	        	'multiple' => true,
	        	'expanded' => true))         
			->add('Edit', 'submit')
	        ->getForm();

        $form->handleRequest($request);
		
		if($document->getDUid() == $this->getUser()->getId()){	
			if ($form->isValid()) {					
				
				$em = $this->getDoctrine()->getManager();
				
				//$em->persist($file);
				$document->setDTitel($form->get('dTitel')->getData());
				$em->flush();
	
				return $this->container
					->get('templating')
					->renderResponse('CadssTestBundle:Default:edit_document.html.twig', array(
						'form' => $form->createView()
					));
			 }
		
    		return $this->render('CadssTestBundle:Default:edit_document.html.twig', array('document' => $document, 'form' => $form->createView()));
		}
		else
		{
			$message = "An error has occurred and the file couldn't be edited";   
			$this->get('session')->getFlashBag()->add('message', $message);
			return $this->redirect($this->generateUrl('cadss_test_homepage'));
		}
	}
	public function deletedocumentAction($id){
        $repositoryDocument = $this->getDoctrine()->getRepository('CadssTestBundle:Document');
        $file = $repositoryDocument->findOneById($id);
        $message = "An error has occurred and the file coudn't be deleted";   
		if(isset($file))  
			if($file->getDUid() == $this->getUser()->getId() && $id!=0){
				$em = $this->getDoctrine()->getManager();
				$em->remove($file);
				$em->flush();
				$message = "Document successfully deleted";             
			}  		
		$this->get('session')->getFlashBag()->add('message', $message);
		return $this->redirect($this->generateUrl('cadss_test_homepage'));       
    }
}